import Router from 'koa-router';
import response from '../../response.js';
import serviceRole from '../../service/role/index.js';

const router = new Router();
router.post('/', async (ctx) => {
  const { roleName, roleCode, description } = ctx.data || {};
  if (!roleName && roleName !== 0) {
    ctx.body = response.fail({ msg: 'roleName not empty' });
    return;
  }
  const createTime = new Date().getTime();
  const result = await serviceRole.save([roleName, createTime, createTime, roleCode, description]);
  if (!result) {
    ctx.body = response.fail({ msg: '新增失败' });
  } else {
    ctx.body = response.success({ msg: '新增成功' });
  }
});
router.get('/', async (ctx) => {
  const list = await serviceRole.getList();
  ctx.body = response.success({ data: { list: list } });
});
router.delete('/:id', async (ctx) => {
  const { id } = ctx.params || {};
  if (!id && id !== 0) {
    ctx.body = response.fail({ msg: '角色id不能为空' });
    return;
  }
  const hasRole = await serviceRole.findById(id);

  if (!hasRole?.length) {
    ctx.body = response.fail({ msg: '数据不存在' });
    return;
  }

  const result = await serviceRole.del(id);
  if (result) {
    ctx.body = response.success({ msg: '删除成功' });
  } else {
    ctx.body = response.fail({ msg: '删除失败' });
  }
});
router.put('/', async (ctx) => {
  const { id, roleName, roleCode = '', description = '' } = ctx.data || {};
  if (!id && id !== 0) {
    ctx.body = response.fail({ msg: '角色id不能为空' });
    return;
  }
  if (!roleName && roleName !== 0) {
    ctx.body = response.fail({ msg: '角色名称不能为空' });
    return;
  }
  const hasRole = await serviceRole.findById(id);
  if (!hasRole?.length) {
    ctx.body = response.fail({ msg: '数据不存在' });
    return;
  }
  const update_time = new Date().getTime();
  const result = await serviceRole.update(
    {
      roleName,
      roleCode,
      description,
      update_time,
    },
    id,
  );
  if (result) {
    ctx.body = response.success({ msg: '更新成功' });
  } else {
    ctx.body = response.fail({ msg: '更新失败' });
  }
});

export default router;
